<template>
  <div class="permission-container">
    <div class="main-content">
      <div class="role-list">
        <!-- 角色表格和分页部分保持不变 -->
        <div v-if="roleLoading" class="table-loading">加载中...</div>

        <el-table
            v-else
            :data="roles"
            border
            stripe
            row-key="id"
            @selection-change="handleRoleSelectionChange"
            style="width: 100% !important;"
        >
          <!-- 表格列定义保持不变 -->
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="roleName" label="角色名称" min-width="120" />
          <el-table-column prop="roleCode" label="角色标识" min-width="120" />
          <el-table-column prop="sum" label="关联用户" width="100" align="center" />
          <el-table-column prop="description" label="角色描述" min-width="150" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <span :class="scope.row.status === '1' ? 'status-enabled' : 'status-disabled'">
                {{ scope.row.status === '1' ? '启用' : '禁用' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="scope">
              <el-button
                  type="primary"
                  size="small"
                  @click="openPermissionDrawer(scope.row)"
                  :icon="Setting"
              >
                配置权限
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
              v-model:current-page="pageNum"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 50]"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalRoles"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 权限配置抽屉 -->
      <el-drawer
          v-model="permissionDrawerVisible"
          :title="'权限配置 - ' + (currentRole.roleName || '')"
          size="70%"
          direction="rtl"
          @close="handleDrawerClose"
      >
        <div v-if="menuLoading" class="permission-loading">权限数据加载中...</div>
        <div v-else-if="hasPermissionData" class="permission-config">
          <div class="permission-section">
            <h3 class="section-title">菜单与按钮权限配置</h3>

            <!-- 使用自定义的树形结构替代el-tree，便于精确控制布局 -->
            <div class="custom-permission-tree">
              <!-- 循环生成一级菜单 -->
              <div v-for="menu in menuTreeData" :key="menu.id" class="first-level-menu">
                <!-- 一级菜单标题 -->
                <div class="first-level-header">
                  <span class="expand-icon">▼</span>
                  <span class="first-level-title">{{ menu.permissionName }}</span>
                  <span class="menu-count">({{ menu.childList ? menu.childList.length : 0 }}项)</span>
                </div>

                <!-- 二级菜单列表 -->
                <div class="second-level-list">
                  <div v-for="subMenu in menu.childList" :key="subMenu.id" class="second-level-item">
                    <div class="menu-item-content">
                      <!-- 菜单名称 -->
                      <span class="second-level-name">{{ subMenu.permissionName }}</span>

                      <!-- 按钮权限区域 -->
                      <div class="button-permissions-group">
                        <el-checkbox
                            v-model="subMenu.permissions.add"
                            :true-label="1"
                            :false-label="0"
                            size="small"
                            class="permission-checkbox"
                            @change="handlePermissionChange"
                        >
                          增加
                        </el-checkbox>
                        <el-checkbox
                            v-model="subMenu.permissions.update"
                            :true-label="1"
                            :false-label="0"
                            size="small"
                            class="permission-checkbox"
                            @change="handlePermissionChange"
                        >
                          修改
                        </el-checkbox>
                        <el-checkbox
                            v-model="subMenu.permissions.delete"
                            :true-label="1"
                            :false-label="0"
                            size="small"
                            class="permission-checkbox"
                            @change="handlePermissionChange"
                        >
                          删除
                        </el-checkbox>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="permission-actions">
            <el-button @click="permissionDrawerVisible = false">取消</el-button>
            <el-button type="primary" @click="savePermissionConfig" :loading="saving">保存权限配置</el-button>
          </div>
        </div>
        <div v-else class="permission-empty">暂无权限数据</div>
      </el-drawer>
    </div>
  </div>
</template>

<script setup>
import { Setting } from '@element-plus/icons-vue'
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import api from "@/utils/request.js";

// 状态变量
const roles = ref([])
const totalRoles = ref(0)
const selectedRoles = ref([])
const currentRole = ref({})
const roleLoading = ref(false)
const saving = ref(false)

// 权限配置相关
const permissionDrawerVisible = ref(false)
const menuLoading = ref(false)
const menuTreeData = ref([])

// 分页变量
const pageNum = ref(1)
const pageSize = ref(10)

// 获取角色列表
const getRoleList = async () => {
  roleLoading.value = true
  try {
    const res = await api.get('/sysPermission/page', {
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
    if (res.code === 200) {
      roles.value = res.data.list.map(role => ({ ...role, status: role.status?.toString() || '0' }))
      totalRoles.value = res.data.total
    } else {
      ElMessage.error(res.msg || '获取角色列表失败')
      roles.value = []
      totalRoles.value = 0
    }
  } catch (err) {
    ElMessage.error('获取角色列表异常，请重试')
    console.error('角色列表请求错误：', err)
  } finally {
    roleLoading.value = false
  }
}

// 获取角色权限数据
const getRolePermissionData = async (roleId) => {
  menuLoading.value = true
  try {
    const menuRes = await api.get('/permission/listByRid', { id: roleId })
    if (menuRes.code !== 200) {
      ElMessage.error(menuRes.msg || '获取角色菜单数据失败')
      return
    }

    // 处理菜单数据，添加权限对象
    menuTreeData.value = processMenuData(menuRes.data || [])

  } catch (err) {
    ElMessage.error('获取角色权限异常，请重试')
    console.error('角色权限请求错误：', err)
  } finally {
    menuLoading.value = false
  }
}

// 处理菜单数据，添加权限对象
const processMenuData = (menuData) => {
  return menuData.map(menu => {
    // 处理一级菜单
    const processedMenu = { ...menu }

    // 处理子菜单
    if (menu.childList && menu.childList.length) {
      processedMenu.childList = menu.childList.map(subMenu => ({
        ...subMenu,
        permissions: {
          add: subMenu.add || 0,
          update: subMenu.update || 0,
          delete: subMenu.delete || 0
        }
      }))
    }

    return processedMenu
  })
}

// 权限变更处理
const handlePermissionChange = () => {
  // 可以在这里添加权限变更的实时处理逻辑
  console.log('权限变更:', menuTreeData.value)
}

// 保存权限配置 - 简化参数格式
const savePermissionConfig = async () => {
  saving.value = true
  try {
    // 构建简化的保存数据结构 - 只包含子菜单ID和权限值列表
    const permissionList = []

    // 遍历所有菜单，只收集二级菜单的权限
    menuTreeData.value.forEach(menu => {
      if (menu.childList && menu.childList.length) {
        menu.childList.forEach(subMenu => {
          permissionList.push({
            menuId: subMenu.id,
            add: subMenu.permissions.add,
            update: subMenu.permissions.update,
            delete: subMenu.permissions.delete
          })
        })
      }
    })

    // 最终发送的数据结构
    const requestData = {
      roleId: currentRole.value.id,
      permissions: permissionList
    }

    console.log('保存权限数据:', JSON.stringify(requestData, null, 2))

    // 发送到接口
    const res = await api.postJson('/permission/savesys', requestData)
    if (res.code === 200) {
      ElMessage.success('权限配置保存成功')
      permissionDrawerVisible.value = false
    } else {
      ElMessage.error(res.msg || '权限配置保存失败')
    }
  } catch (err) {
    ElMessage.error('权限配置保存异常，请重试')
    console.error('权限保存错误：', err)
  } finally {
    saving.value = false
  }
}

// 重置权限数据
const resetPermissionData = () => {
  menuTreeData.value = []
}

// 打开权限抽屉
const openPermissionDrawer = (role) => {
  if (!role?.id) {
    ElMessage.warning('请选择有效的角色')
    return
  }
  currentRole.value = { ...role }
  permissionDrawerVisible.value = true
  resetPermissionData()
  getRolePermissionData(role.id)
}

// 处理抽屉关闭
const handleDrawerClose = () => {
  resetPermissionData()
  permissionDrawerVisible.value = false
}

// 检查是否有权限数据
const hasPermissionData = computed(() => {
  return menuTreeData.value && menuTreeData.value.length > 0
})

// 角色选择变化
const handleRoleSelectionChange = (val) => {
  selectedRoles.value = val
}

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val
  pageNum.value = 1
  getRoleList()
}
const handleCurrentChange = (val) => {
  pageNum.value = val
  getRoleList()
}

onMounted(() => {
  getRoleList()
})
</script>

<style scoped>
.permission-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
  box-sizing: border-box;
}

.main-content {
  width: 100%;
  box-sizing: border-box;
}

.role-list {
  width: 100%;
  box-sizing: border-box;
}

.table-loading, .permission-loading, .permission-empty {
  text-align: center;
  padding: 50px 0;
  color: #606266;
  font-size: 14px;
}

.status-enabled {
  color: #10b981;
  font-weight: 500;
}
.status-disabled {
  color: #ef4444;
  font-weight: 500;
}

.permission-config {
  padding: 10px 0;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.permission-section {
  background-color: #f8f9fa;
  padding: 0;
  border-radius: 4px;
  margin-bottom: 20px;
  flex: 1;
  overflow: auto;
}

.section-title {
  margin: 0 0 15px 0;
  padding: 15px 20px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2329;
  border-bottom: 1px solid #e8e8e8;
  background-color: #fff;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
  padding: 10px 0;
}

/* 自定义权限树形结构样式 */
.custom-permission-tree {
  padding: 0;
}

.first-level-menu {
  margin-bottom: 0;
  border-bottom: 1px solid #f0f0f0;
}

.first-level-menu:last-child {
  border-bottom: none;
}

.first-level-header {
  padding: 12px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e8e8e8;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.expand-icon {
  margin-right: 8px;
  font-size: 12px;
  color: #666;
  transition: transform 0.2s;
}

.first-level-title {
  font-size: 14px;
  font-weight: 600;
  margin-right: 8px;
}

.menu-count {
  font-size: 12px;
  color: #666;
  background-color: #e9ecef;
  padding: 2px 8px;
  border-radius: 10px;
}

.second-level-list {
  background-color: #fff;
}

.second-level-item {
  border-bottom: 1px solid #f8f8f8;
  transition: background-color 0.2s;
}

.second-level-item:hover {
  background-color: #f8f9fa;
}

.second-level-item:last-child {
  border-bottom: none;
}

/* 核心修复：菜单项内容水平布局 */
.menu-item-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px 12px 40px; /* 二级菜单缩进 */
  min-height: 44px;
  box-sizing: border-box;
  gap: 20px; /* 菜单名称和按钮区域之间的间距 */
}

.second-level-name {
  font-size: 14px;
  color: #333;
  min-width: 120px; /* 固定菜单名称最小宽度 */
  flex-shrink: 0; /* 防止菜单名称被压缩 */
  font-weight: 500;
}

/* 按钮权限区域水平排列 */
.button-permissions-group {
  display: flex;
  align-items: center;
  gap: 20px; /* 按钮之间的间距 */
  flex-wrap: nowrap; /* 禁止换行 */
  flex-shrink: 0; /* 防止按钮区域被压缩 */
  margin-left: auto; /* 靠右对齐 */
}

.permission-checkbox {
  margin: 0;
  white-space: nowrap;
}

.permission-checkbox :deep(.el-checkbox__label) {
  font-size: 13px;
  color: #666;
  padding-left: 6px;
}

.permission-actions {
  margin-top: 20px;
  text-align: right;
  padding: 15px 0;
  border-top: 1px solid #ebeef5;
  background-color: #fff;
}

/* 复选框样式优化 */
:deep(.el-checkbox) {
  margin-right: 0;
}

:deep(.el-checkbox__input) {
  margin-right: 4px;
}

/* 滚动条样式 */
.permission-section::-webkit-scrollbar {
  width: 6px;
}

.permission-section::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.permission-section::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.permission-section::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .menu-item-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    padding-left: 30px;
  }

  .button-permissions-group {
    margin-left: 0;
    justify-content: flex-start;
    width: 100%;
    flex-wrap: wrap;
    gap: 15px;
  }

  .permission-container {
    padding: 10px;
  }

  .second-level-name {
    min-width: auto;
  }
}

/* 大屏幕优化 */
@media (min-width: 1200px) {
  .menu-item-content {
    gap: 30px;
  }

  .button-permissions-group {
    gap: 25px;
  }
}
</style>